;get filenames of image files to be processed
filenames = dialog_pickfile(/multiple_files, filter = '*.fits', $
                            title = 'FITS files to be pre-processed')
;how many images?
nimages = n_elements(filenames)
;get filename of dark file to subtract
dark = dialog_pickfile(title = 'dark FITS file', filter = '*.fits')
;get path where dark-subtracted files are to be written
ds_path = dialog_pickfile(title = $
                          'choose directory to write dark-subracted FITS', $
                          /directory)
;read in dark image, convert to float
dark = float(mrdfits(dark, 0, darkhead, /unsigned))

sky_med=0.0

FOR i = 0, nimages-1 DO BEGIN   ;for each image file
;read in image, conver to float; get header as well
   image = float(mrdfits(filenames[i], 0, header, /unsigned))
;subtract dark image
   image_ds = image-dark
;calculate the median of the sky (dark subtracted image)
   ;sky_med=float(nimages)
   sky_med += median(image_ds)
ENDFOR

sky_mean=sky_med/nimages

FOR i = 0, nimages-1 DO BEGIN   ;for each image file
;read in image, conver to float; get header as well
   image = float(mrdfits(filenames[i], 0, header, /unsigned))
;subtract dark image
   image_ds = image-dark
;strip directory path from image filename (oth element)
   file_nopath = reverse(strsplit(filenames[i], '/', /extract))
;strip off .fits suffix
   file_begin = strsplit(file_nopath[0], '.fits', /extract, /regex)
;add write path and _pp.fits suffix
   ds_filename = file_begin[0] + '_pp.fits'
;take median again
   im_med=median(image_ds)
   image_pp=image_ds*(sky_mean/im_med)

;write dark-subtracted and replateaued image and original image header to file
   print, 'WRITING TO ' + ds_filename
   mwrfits, image_pp, ds_filename, header

ENDFOR


END
